//
//  XMComposeView.swift
//  XMWeimo
//
//  Created by ios001 on 16/7/28.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import pop

class XMComposeView: UIView {
    
    // 代表记录MainVc
    var target: UIViewController?
    
    // 保存compose 数组
    lazy var composeButtonInfos:[XMComposeButtonInfo] = [XMComposeButtonInfo]()
    
    // 保存按钮数组
    lazy var buttons: [XMComposeButton] = [XMComposeButton]()

    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: SCREENW, height: SCREENH))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK: - 监听方法
    func buttonClick(button: XMComposeButton) {
        // 设置动画
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            // 遍历保存按钮数组
            for value in self.buttons {
                // 设置透明度
                value.alpha = 0.2
                // 判断遍历到的按钮是否是当前点击的按钮
                if value == button {
                    value.transform = CGAffineTransformMakeScale(2,2)
                }else {
                    value.transform = CGAffineTransformMakeScale(0.2,0.2)
                }
            }
            }) { (_) -> Void in
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    // 遍历保存按钮数组
                    for value in self.buttons {
                        value.alpha = 1
                        value.transform = CGAffineTransformIdentity
                        }
                    }, completion: { (_) -> Void in
                        guard let vcName = button.composeButtonInfo?.nextvc else{
                            return
                        }

                        guard let pn = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as?String else{
                            return
                        }

                        // 判断class 是否为nil 而且是否可以转成UIViewController.Type
                        // 为什么 “SHComposeViewController” 因为OC中根本没有命名空间 而Swift中有命名空间
//                        // 如果Swift中获取自定义类的class [项目名.类名]

                        guard let cn = NSClassFromString("\(pn).\(vcName)") as? UIViewController.Type else {
                            return
                        }
                        // 初始化
                        let tempVc = cn.init()
                        let naVc = UINavigationController(rootViewController: tempVc)
                        self.target?.presentViewController(naVc, animated: true, completion: { () -> Void in
                            self.removeFromSuperview()
                        })
                })
        }
    }
    
    // 添加composeViewShow
    func composeViewShow(target: UIViewController){
        // 赋值
        self.target = target
        target.view.addSubview(self)
        setUpButtonsAnim(true)
    }
    

    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = RandomColor()
        // 添加控件
        addSubview(bgImageView)
        addSubview(logoImageView)
        addChildButtons()
        
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        
        logoImageView.snp_makeConstraints(closure: { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        })
        }
    }
    // 创建子控件 button
    func addChildButtons(){
        composeButtonInfos = getCoposeButtonInfos()
        // 按钮的宽和高
        let childW: CGFloat = 80
        let childH: CGFloat = 110
        // 按钮间距
        let childMargin: CGFloat = (SCREENW - childW*3)/4
        
        for (i,value) in composeButtonInfos.enumerate() {
            // 得到行数和列数
            let col = CGFloat(i%3)
            let row = CGFloat(i/3)
            // 创建button
            let button = XMComposeButton()
            // button属性赋值
            button.composeButtonInfo = value
            //button 添加点击事件 **又忘记加:号
            button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            button.setImage(UIImage(named: value.icon ?? ""), forState: UIControlState.Normal)
            button.setTitle(value.title, forState: UIControlState.Normal)

            button.frame = CGRect(x: childMargin + (childW+childMargin)*col, y: (childH+childMargin)*row+SCREENH, width: childW, height: childH)
            addSubview(button)
            // 保存按钮
            buttons.append(button)

        }
    }

    // 读取plist文件 得到数据
    func getCoposeButtonInfos()->[XMComposeButtonInfo]{
        // 获取路径
        let file = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        // pliset文件转数组
        let array = NSArray(contentsOfFile: file)!
        // 创建一个可变数组
        var tempArray:[XMComposeButtonInfo] = [XMComposeButtonInfo]()
        
        // 遍历array 字典转模型
        for dic in array {
            // 创建模型
            let composeButtonInfo = XMComposeButtonInfo(dict: dic as! [String: AnyObject])
            // 添加模型
            tempArray.append(composeButtonInfo)
        }
        return tempArray
    }
    
    // 点击屏幕 view消失
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        setUpButtonsAnim(false)
           // 延迟删除当前的view
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
                self.removeFromSuperview()
        }
    }
    
    // 设置buttons动画 (isup==true代表向上显示按钮 false代表消失按钮)
    func setUpButtonsAnim(isUp: Bool){
        // 距离
        let margin: CGFloat = isUp ? -350 : 350
        // 数组集合
        let set = isUp ? buttons.enumerate() : buttons.reverse().enumerate()
        
        // 遍历按钮数组,分别设置动画
        for (i,value) in set {
            // 设置动画
            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            // 设置tovalue
            anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + margin))
            // 开始时间
            anim.beginTime = CACurrentMediaTime() + Double(i)*0.025
            // 弹性系数
            anim.springBounciness = 10
            // 动画速度
            anim.springSpeed = 8
            value.pop_addAnimation(anim, forKey: nil)
        }

    }
    
    // MARK: - 懒加载控件
    // 背景磨砂图片
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    private lazy var logoImageView: UIImageView = UIImageView(imgName: "compose_slogan")
}
